package com.msblearn.C_008;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 不使用synchonized.使用reentrantLock
 *
 * @param <T>
 */
public class T_MyContainer2<T> {
    final private LinkedList<T> linkedList = new LinkedList<T>();
    final private int Max = 10;
    private int count = 0;

    private Lock lock = new ReentrantLock();
    //等待队列
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(T t) {
        //为啥用while而不用if.
        //不行。
        try {
            lock.lock();
            while (linkedList.size() == Max) {
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            linkedList.add(t);
            ++count;
            consumer.signalAll();
        } finally {
            lock.unlock();
        }


    }

    public T get() {
        T t = null;
        try {
            lock.lock();
            while (linkedList.size() == 0) {
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            t = linkedList.removeFirst();
            count--;
            producer.signalAll();
        }
        finally {
            lock.unlock();
        }

        return t;
    }

    public static void main(String[] args) {
        T_MyContainer2<String> tt = new T_MyContainer2<>();
        //启动消费者线程
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(tt.get());
                }
            }, "T" + i).start();
        }

        //启动生产者线程
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 23; j++) {
                    tt.put(Thread.currentThread().getName() + " " + j);
                }
            }, "TT").start();
        }
    }
}
